package main

import (
    "fmt"
    "io"
    "net"
    "os"
)

func recieveFile(fileName string, conn net.Conn){
    f,errCreate:=os.Create(fileName)
    if errCreate!=nil{
        fmt.Println("Create Err:",errCreate)
        return
    }
    buf:=make([]byte,1024*4)
    for{
    	n,errRead:=conn.Read(buf)
    	if errRead!=nil{
    	    if errRead==io.EOF{
    	        fmt.Println("文件接收完毕")
            }else{
                fmt.Println("文件接收错误")
            }
            return
        }
    	_,errWrite:=f.Write(buf[:n])
    	if errWrite != nil{
    	    fmt.Println("文件写入错误")
    	    return
        }
	}
}

func main()  {
    listener,err:=net.Listen("tcp","127.0.0.1:8000")
    defer listener.Close()
    if err!=nil{
        fmt.Println("listener Err:",err)
        return
    }
    conn,errConn:=listener.Accept()
    defer conn.Close()
    if errConn!=nil{
        fmt.Println("Conn Err:",errConn)
        return
    }
    buf:=make([]byte,1024)
    n,errRead:=conn.Read(buf)
    if errRead != nil{
        fmt.Println("Read Err:",errRead)
        return
    }
    fileName := string(buf[:n])
    _,errWrite:=conn.Write([]byte("ok"))
    if errWrite!=nil{
        fmt.Println("Write Err:",errWrite)
        return
    }
    recieveFile(fileName,conn)

}
